package com.inepex.graphicstests.client.misc.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.TextBox;

public class NumericTextBox extends TextBox {
	
	protected int defaultValue;
	
	public NumericTextBox(int defaultValue) {
		super();
		this.defaultValue = defaultValue;
		KeyPressHandler validator = new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				char keyCode = event.getCharCode();	
				if (!Character.isDigit(keyCode) && (keyCode != 127 || keyCode != 8)){
					((TextBox)event.getSource()).cancelKey();
				}
			}
		};
		ClickHandler clickClear = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				((TextBox)event.getSource()).setText("");				
			}
		};
		addClickHandler(clickClear);
		addKeyPressHandler(validator);
		setValue(defaultValue+"");
	}

	public int parseIntValue(){
		int i;
		try{
			i = Integer.parseInt(getText());
		}
		catch (Exception e) {
			i = defaultValue;
			setValue(defaultValue+"");
		}
		return i;
	}
}
